package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.Book;
import exception.FindProductByIdException;
import service.ProductService;

/**
 * Servlet implementation class AddCartServlet
 */
public class AddCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 1.得到商品id
				String id = request.getParameter("id");
				// 2.调用service层方法，根据id查找商品
				ProductService service = new ProductService();
				try {
					Book p = service.findProductById(id);
					//3.1获得session对象
					HttpSession session = request.getSession();
					//3.2从session中获取购物车对象
					@SuppressWarnings("unchecked")
					Map<Book, Integer> cart = (Map<Book, Integer>)session.getAttribute("cart");
					//3.3判断购物车是否有商品
					if (cart == null) {
						cart = new HashMap<Book, Integer>();
					}
					//3.4向购物车中添加商品
					Integer count = cart.put(p,1);
					//首次添加商品
					if (count != null) {
						cart.put(p,count+1);
					}			
					session.setAttribute("cart", cart);
					response.sendRedirect(request.getContextPath() + "/client/cart.jsp");
					return;
				} catch (FindProductByIdException e) {
					// TODO Auto-generated catch block
					response.getWriter().print(e.getMessage());
				}
	}

}
